from server import app
from server.api import init_api_route
from server.app import init_app_route

from flask import Flask, request, jsonify
import hashlib
import os

init_api_route(app)
init_app_route(app)


@app.route('/hello', methods=['GET'])
def hello():
    return "hello"


def check_signature(signature, timestamp, nonce, token):
    tmp_arr = [token, timestamp, nonce]
    tmp_arr.sort()
    tmp_str = ''.join(tmp_arr)
    tmp_str = hashlib.sha1(tmp_str.encode('utf-8')).hexdigest()
    print('signature:', signature)
    print('tmp_str:', tmp_str)
    return tmp_str == signature


@app.route('/check_token', methods=['GET'])
def check_token():
    signature = request.args.get("signature")
    timestamp = request.args.get("timestamp")
    nonce = request.args.get("nonce")
    echostr = request.args.get("echostr")

    if not all([signature, timestamp, nonce]):
        return jsonify({'code': 400, 'message': 'Missing parameters'}), 400
    TOKEN = os.getenv("G_TOKEN")
    if check_signature(signature, timestamp, nonce, TOKEN):
        return echostr
    else:
        return 'Invalid request'


# 设置静态文件的URL前缀，默认为 "/static"
app.static_url_path = '/static'

# 设置静态文件的目录，默认为应用程序的 "static" 文件夹
app.static_folder = 'static'


# 添加路由，用于访问静态文件
@app.route('/static/<path:filename>')
def custom_static(filename):
    return app.send_static_file(filename)


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=app.config['PORT'])
